package com.ruoyi.web.controller.ring.app;

import cn.hutool.core.convert.Convert;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.bean.Builder;
import com.ruoyi.ring.domain.RingEventInfo;
import com.ruoyi.ring.domain.dto.RingEventInfoAddDTO;
import com.ruoyi.ring.service.IRingEventInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 活动信息 （APP）
 */
@Slf4j
@RestController
@RequestMapping("/ring/app/ring_event_info")
public class AppEventInfoController extends BaseController
{
    @Resource
    private IRingEventInfoService ringEventInfoService;

    /**
     * 新增活动信息-app
     */
    @PostMapping("/add-event-info")
    public AjaxResult addEventInfo(@RequestBody RingEventInfoAddDTO addDTO){
        String deviceSn = addDTO.getDeviceSn();
        try {
            List<RingEventInfoAddDTO.StressDTO> stressDTOList = addDTO.getStress();
            stressDTOList.forEach(stressDTO -> {
                Date dailyValue = stressDTO.getDailyValue();
                RingEventInfo eventInfo = ringEventInfoService.selectOneRingEventInfo(Builder.of(RingEventInfo::new).
                        with(RingEventInfo::setDeviceSn, deviceSn).
                        with(RingEventInfo::setDailyValue, dailyValue).build());
                RingEventInfo ringEventInfo = Convert.convert(RingEventInfo.class,stressDTO);
                if(eventInfo != null){
                    ringEventInfo.setId(eventInfo.getId());
                    ringEventInfo.setDeviceSn(deviceSn);
                    ringEventInfoService.updateRingEventInfo(ringEventInfo);
                }else {
                    if(!"".equals(ringEventInfo.getEventContent()) && ringEventInfo.getEventContent() != null){
                        ringEventInfo.setDeviceSn(deviceSn);
                        ringEventInfoService.insertRingEventInfo(ringEventInfo);
                    }
                }
            });

            return AjaxResult.success();
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("上报活动信息失败！");
        }
    }
}
